package com.mark.mall.web.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageMethod;
import com.google.common.collect.Lists;
import com.mark.mall.common.constans.PlatformConstant;
import com.mark.mall.common.myException.MyException;
import com.mark.mall.common.resultBean.R;
import com.mark.mall.web.platform.dto.PageParamDTO;
import com.mark.mall.web.platform.dto.ProductDTO;
import com.mark.mall.web.platform.entity.Product;
import com.mark.mall.web.platform.mapper.ProductMapper;
import com.mark.mall.web.platform.service.ProductService;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;


/**
 * <p>
 * 物料表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-03-03
 */
@Service
@RequiredArgsConstructor
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    private final RestHighLevelClient restHighLevelClient;

    @Override
    public R<PageInfo<ProductDTO>> listProductPageInfo(PageParamDTO param, String searchName) {
        PageInfo<ProductDTO> pageInfo = PageMethod.startPage(param.getPageNo(), param.getPageSize())
                .doSelectPageInfo(
                        () -> list(Wrappers.<Product>lambdaQuery()
                                .like(StrUtil.isNotBlank(searchName), Product::getName, searchName))
                );
        return new R<>(pageInfo);
    }

    @Override
    public R<Product> productDetail(String id) {
        if (StrUtil.isBlank(id)) {
            throw new MyException("参数缺失，请核实！");
        }
        return new R<>(
                baseMapper.selectById(id)
        );
    }

    @Override
    public R<PageInfo<Product>> searchDate(PageParamDTO param, String searchThing) throws IOException {
        SearchRequest request = new SearchRequest(PlatformConstant.INDEX_NAME);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // es分页起始为0
        builder.from(param.getPageNo() - 1);
        builder.size(param.getPageSize());
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 根据查询条件搜索
        if(StrUtil.isNotBlank(searchThing)){
            boolQueryBuilder.should(QueryBuilders.matchPhraseQuery("name",searchThing))
                            .should(QueryBuilders.wildcardQuery("code",("*" + searchThing + "*").toLowerCase()));
        }
        builder.query(boolQueryBuilder);
        request.source(builder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        List<Product> list = Lists.newArrayList();
        for (SearchHit hit : search.getHits().getHits()) {
            Product product = JSONObject.toJavaObject(new JSONObject(hit.getSourceAsMap()), Product.class);
            if (product == null) continue;
            list.add(product);
        }
        PageInfo<Product> pageInfo = new PageInfo<>();
        pageInfo.setList(list);
        // 此处需要将总数返回，否则返回的total数量不对
        pageInfo.setTotal(search.getHits().getTotalHits().value);
        return new R<>(pageInfo);
    }
}

